//
//  RegistereViewModel.m
//  GLGW_Shoping
//
//  Created by yang on 2018/11/15.
//  Copyright © 2018年 yang. All rights reserved.
//

#import "RegistereViewModel.h"
#import "VerificationCodeTableViewCell.h"
#import "LoginActionTableViewCell.h"
#import "RegistereFootView.h"
#import "RegistereModel.h"
#import "LoginModel.h"

@interface RegistereViewModel ()<UITableViewDelegate,UITableViewDataSource,RegistereCellDelegate>{
    //填写的三个str
    NSString * phoneStr;//
    NSString * imageStr;//
    NSString * codeStr;//
    //
    NSString * trueCodeStr;
    //
    GLGWButton * comintBut;
    //
    RegistereModel * regModel;//图片验证码model
    GLGWImageView * picCodeImageView;
}
@end

@implementation RegistereViewModel


-(instancetype)initWithViewToViewModel:(UITableView *)tableView theSuperView:(UIView *)superView{
    if (self = [super initWithViewToViewModel:tableView theSuperView:superView]) {
        tableView.mj_footer.hidden = YES;
        tableView.mj_header.hidden = YES;
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, kHeightProportion_In_iPhoneTriploid(65))];
        tableView.tableFooterView = [self registereFootView:tableView];
        [superView addSubview:tableView];
        //
        [self requestPicCode];
    }
    return self;
}

-(UIView *)registereFootView:(UITableView *)m_tableView{
    RegistereFootView * footView = [[RegistereFootView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, m_tableView.height-kHeightProportion_In_iPhoneTriploid(350))];
    return footView;
}
#pragma mark -- UITableViewDelegate,UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 4;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 3) {
        return kHeightProportion_In_iPhoneTriploid(94);
    }else{
        return kHeightProportion_In_iPhoneTriploid(62);
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BaseTableViewCell * cell;
    switch (indexPath.row) {
        case 0:
        case 1:
        case 2:{
            NSString * mark = NSStringFromClass([VerificationCodeTableViewCell class]);
            VerificationCodeTableViewCell *cell_ver = [tableView dequeueReusableCellWithIdentifier:mark];
            if (!cell_ver) {
                cell_ver = [[VerificationCodeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:mark thrRow:indexPath.row];
            }
            if (indexPath.row == 1) {
                picCodeImageView = cell_ver.codePictureImageView;
            }
            cell_ver.delegate = self;
            cell = cell_ver;
        }
            break;
        case 3:{
            LoginActionTableViewCell * cell_But = [LoginActionTableViewCell cellWithTableView:tableView];
            comintBut = cell_But.actionBut;
            comintBut.title = @"完成";
            [comintBut addTarget:self action:@selector(reqisterAction) forControlEvents:UIControlEventTouchUpInside];
            cell = cell_But;
        }
            break;
            
        default:
            break;
    }
    return cell;
}

-(void)reqisterAction{
//    DLog(@"注册");
    if (![imageStr isEqualToString:regModel.data.verifyCode]) {
        [GLGWProgressHUD showNotice:@"图片验证码不正确！" view:nil];
        return;
    }
    if (![trueCodeStr isEqualToString:codeStr]) {
        [GLGWProgressHUD showNotice:@"短信验证码不正确！" view:nil];
        return;
    }
    NSMutableDictionary * parDic = [NSMutableDictionary dictionaryWithDictionary:@{@"mobilePhone":koString(phoneStr),
                                                                                   @"registerType":@3,
                                                                                   @"type":@1,
                                                                                   @"code":koString(trueCodeStr)}];
    if (_regis_type == RegisterePushType_BindingPhone) {
        [self thireReginsData:parDic];
    }else{
        if (self.delegate && [self.delegate respondsToSelector:@selector(setAccountPassword:)]) {
            [self.delegate setAccountPassword:parDic];
        }
    }
}
#pragma mark --- RegistereCellDelegate
-(void)phoneNumStr:(NSString *)p_str picVerification:(NSString *)v_str codeString:(NSString *)c_str{
    phoneStr = p_str;
    imageStr = v_str;
    codeStr = c_str;
    if (p_str.length>0 && v_str.length>0 && c_str.length>0) {
        comintBut.backgroundColor = kColor_Rule_Yellow;
        comintBut.enabled = YES;
    }else{
        comintBut.backgroundColor = [UIColor colorWithHexString:@"#CCCCCC"];
        comintBut.enabled = NO;
    }
}

-(void)verificationCode:(GLGWButton *)ver_but{
    if (phoneStr.length == 0) {
        return;
    }
    __block int timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout == 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                ver_but.title = @"获取验证码";
                [ver_but setTitleColor:kColor_Rule_Yellow forState:UIControlStateNormal];
                ver_but.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(),^{
                ver_but.title = [NSString stringWithFormat:@"%@s",strTime];
                [ver_but setTitleColor:[UIColor colorWithHexString:@"#999999"] forState:UIControlStateNormal];
                ver_but.userInteractionEnabled = NO;
                if (seconds ==59){
                    [self requestPhoneCode];
                }
            });
            if(timeout > 0) {
                timeout--;
            }
        }
    });
    dispatch_resume(_timer);
}

-(void)changeVerificationCode{
    [self requestPicCode];
}
#pragma mark =================== 数据请求 ===================
-(void)requestPhoneCode{
    NSDictionary * dic = @{@"mobilePhone":koString(phoneStr)};
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kPhoneCode] lodingView:nil lodingTextString:@"" isLoding:YES parameters:dic success:^(id  _Nullable response) {
        NSDictionary * dic = response;
        NSString * messageCode = [dic objectForKey:@"data"];
        self->trueCodeStr = messageCode;
    } failure:^(NSError * _Nullable error) {

    }];
}

-(void)requestPicCode{
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kPictureCode] lodingView:nil lodingTextString:@"" isLoding:YES parameters:@{} success:^(id  _Nullable response) {
        self->regModel = [RegistereModel yy_modelWithJSON:response];
        NSString *string =self->regModel.data.qrPicture;
        NSRange range = [string rangeOfString:@"base64,"];//匹配得到的下标
        NSString *str1 = [string substringFromIndex:(range.location + range.length)];//截取掉下标之前的字符串
        NSData *decodeData = [[NSData alloc]initWithBase64EncodedString:str1 options:(NSDataBase64DecodingIgnoreUnknownCharacters)];
        // 将NSData转为UIImage
        UIImage *decodedImage = [UIImage imageWithData: decodeData];
        self->picCodeImageView.image = decodedImage;
    } failure:^(NSError * _Nullable error) {
        
    }];
}

-(void)thireReginsData:(NSMutableDictionary *)dic{
    [_requestDic addEntriesFromDictionary:[dic mutableCopy]];
    
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kThridBindRegistor] lodingView:nil lodingTextString:@"" isLoding:YES parameters:_requestDic success:^(id  _Nullable response) {
        LoginModel * l_model = [LoginModel yy_modelWithJSON:response];
        if (l_model.code == 0) {
            NSData * userData = [NSKeyedArchiver archivedDataWithRootObject:l_model];
            self.userInforData = userData;
            self.userId = l_model.data.userId;
            if (self.delegate && [self.delegate respondsToSelector:@selector(popRootViewController)]) {
                [self.delegate popRootViewController];
            }
        }
    } failure:^(NSError * _Nullable error) {
        
    }];
}

#pragma mark ---  set
-(void)setRegis_type:(RegisterePushType)regis_type{
    _regis_type = regis_type;
}

-(void)setRequestDic:(NSMutableDictionary *)requestDic{
    _requestDic = requestDic;
}

@end
